package com.iwhalecloud.bss.kite.cucc.service.attr.handler;

import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.DecimalCalc;
import com.iwhalecloud.bss.kite.cucc.service.attr.linkhandler.LocalSubscriptionFeeAttrLinkHandler;
import com.iwhalecloud.bss.kite.cucc.spec.impl.transfer.GoodsInfoTransfer;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.cache.ProductCache;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.dto.KiteInstRelDTO;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInstFunc;
import com.iwhalecloud.bss.kite.service.attr.AttrData;
import com.iwhalecloud.bss.kite.service.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class lnfinityGradeCostAttrHandler extends AbstractAttrHandler<KiteProdInstFunc, AttrData> {

    @Autowired
    private IQuerySceneInstService querySceneInstService;


    @Override
    public void onShow(KiteAttr attr, KiteProdInstFunc inst, AttrData data) {
        KiteProdInst prodInst = querySceneInstService.getProdInstByFuncProdInstId(data.getCustId(),inst.getInstId());
        if(KiteObjectUtils.isEmpty(prodInst)){
            return;
        }
        List<KiteProdInstFunc> funcs = querySceneInstService.listProdInstFuncsBySceneInstId(prodInst.getProdInstId(),data.getSceneInstId());
        if(KiteListUtils.isNotEmpty(funcs)){
            String communicationPacketType = "";
            for(KiteProdInstFunc func : funcs){
                //通信套包类型
                KiteAttr kiteAttr = func.getAttr("200003697");
                if (Objects.isNull(kiteAttr)) {
                    // 资费套包类型
                    kiteAttr = func.getAttr("200004179");
                }
                if(!KiteObjectUtils.isEmpty(kiteAttr)){
                    communicationPacketType = kiteAttr.getValue();
                }
            }
            //折扣类型
            String discountType = "";
            KiteAttr kiteAttr = inst.getAttr("200003712");
            if(!KiteObjectUtils.isEmpty(kiteAttr)){
                discountType = kiteAttr.getValue();
            }
            //通信套包类型 月付固定共享、预付固定共享
            if(!(KiteStringUtils.equals("100007469",communicationPacketType)||KiteStringUtils.equals("100007470",communicationPacketType))){
                //折扣类型为一口价时展示0-∞万户数量档最终账户费(元)
                if(KiteStringUtils.equals("100006437",discountType)){
                    attr.setShowType(KeyConsts.PROD_ATTR_SHOW_TYPE_D);
                }else{
                    attr.setShowType(KeyConsts.PROD_ATTR_SHOW_TYPE_E);
                }
            }else {
                attr.setShowType(KeyConsts.PROD_ATTR_SHOW_TYPE_E);
            }
        }
    }

    @Override
    public void set(KiteAttr attr, KiteProdInstFunc inst, String value, AttrData data) {
        super.set(attr, inst, value, data);
        //模版还原时，重提还原，不计算
        Map<String, Object> extParams = ContextUtil.getLoginInfo().getUserInfo().getExtParams();
        if ("sceneTempl".equals(data.getExtAttributes().get("entry")) || (KiteMapUtils.isNotEmpty(extParams) && extParams.containsKey("nodeCode"))) {
            return;
        }
        //变更业务的场景初始化过程中不进行计算
        if (ServiceOfferConsts.SERVICE_OFFER_MODIFY.equals(data.getServiceOfferId())
            && !KeyConsts.IFTRUE_T.equals(querySceneInstService.getExtParameterValue(data.getSceneInstId(), LocalKeyConsts.BUSI_CHANGE))
            && !"workOrder".equals(querySceneInstService.getExtParameterValue(data.getSceneInstId(), "initSource"))) {
            return;
        }
        this.calculate(attr, inst, value, data);
    }

    /**
     * 折扣率计算
     * @param attr
     * @param inst
     * @param value
     * @param data
     */
    public void calculate(KiteAttr attr, KiteProdInstFunc inst, String value, AttrData data) {
        //订购-资费计划折扣信息的折扣率应自动计算，不是手输，计算公式为：折扣率=最终订购费/[标准价格*灵活共享系数*(1+平台功能费%)]，分档折扣取第一档的最终订购费
        List<KiteInstRelDTO> prodInstRels = querySceneInstService.listInstRelsByZInst(data.getCustId(), InstType.PROD_INST_FUNC, inst.getInstId(), InstType.PROD_INST);
        if (KiteListUtils.isEmpty(prodInstRels)) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("产品实例不能为空");
        }
        KiteProdInst accProdInst = this.querySceneInstService.getProdInst(data.getCustId(), prodInstRels.get(0).getaInstId());
        String accProdInstId = accProdInst.getProdInstId();
        //折扣率
        KiteAttr discountAttr = this.getDiscountRateAttr(inst, accProdInstId, data.getCustId());
        if (discountAttr == null) {
            return ;
        }
        //灵活共享系数
        Double shareRate = this.getShareRate(inst);
        //标准价格200002773
        Double totalStandarPrice = this.sumTotalStandarPrice(data.getSceneInstId(), accProdInstId, data.getCustId());
        Double platFromFuncFee = this.getPlatformFuncFee(data.getSceneInstId(), data.getCustId());
        Double orderPrice = this.getOrderPrice(discountAttr, inst, data.getCustId(), accProdInstId, data.getSceneInstId());
        this.calculateDiscountRate(inst, discountAttr, data, totalStandarPrice, platFromFuncFee, orderPrice, shareRate);
    }

    /**
     * 获取总标准价格
     * @param accProdInstId
     * @param custId
     * @return
     */
    private Double sumTotalStandarPrice(String sceneInstId, String accProdInstId, String custId) {
        String basePriceFieldName = "200002773";
        //标准价格200002773
        Double totalStandarPrice = 0D;
        List<KiteInstRelDTO> prodInstFuncRels = querySceneInstService.listInstRelsByAInst(custId, InstType.PROD_INST, accProdInstId, InstType.PROD_INST_FUNC);
        for (KiteInstRelDTO funcRel : prodInstFuncRels) {
            KiteProdInstFunc func = this.querySceneInstService.getProdInstFunc(custId, funcRel.getzInstId());
            // 资费服务信息
            if (KiteStringUtils.equalsAny(ProductCache.get(func.getSpecId()).getProdNbr(), "300000170", LocalKeyConsts.FUNC_PROD_ID_YF5GZF_BASE)) {
                if (KiteStringUtils.equalsAny(func.getAttrValue("200003697"), "100006433", "100006434")) {
                    basePriceFieldName = "210005341";
                    break;
                }
            }
        }
        for (KiteInstRelDTO funcRel : prodInstFuncRels) {
            KiteProdInstFunc func = this.querySceneInstService.getProdInstFunc(custId, funcRel.getzInstId());
            if (KiteObjectUtils.isEmpty(ProductCache.get(func.getSpecId()))) {
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("请刷新产品缓存");
            }
            // 资费服务信息
            if (KiteStringUtils.equalsAny(ProductCache.get(func.getSpecId()).getProdNbr(), "300000171", LocalKeyConsts.FUNC_PROD_ID_YF5GZF_FW)) {
                //标准价格
                String standarPrice = KiteStringUtils.isEmpty(func.getAttrValue(basePriceFieldName)) ? KeyConsts.ZERO : func.getAttrValue(basePriceFieldName);
                totalStandarPrice += Double.valueOf(standarPrice);
            }
        }

        return totalStandarPrice;
    }

    /**
     * 最终订购价
     * @param attr
     * @param inst
     * @return
     */
    private Double getOrderPrice(KiteAttr attr, KiteProdInstFunc inst, String custId, String accProdInstId, String sceneInstId) {
        if (KiteObjectUtils.isEmpty(ProductCache.get(inst.getSpecId()))) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("请刷新产品缓存");
        }
        if (!KiteStringUtils.equalsAny(ProductCache.get(inst.getSpecId()).getProdNbr(), "300000172", LocalKeyConsts.FUNC_PROD_ID_YF5GZF_ZK)) {
            List<KiteInstRelDTO> prodInstFuncRels = querySceneInstService.listInstRelsByAInst(custId, InstType.PROD_INST, accProdInstId, InstType.PROD_INST_FUNC);
            for (KiteInstRelDTO funcRel : prodInstFuncRels) {
                KiteProdInstFunc func = this.querySceneInstService.getProdInstFunc(custId, funcRel.getzInstId());
                if (KiteObjectUtils.isEmpty(ProductCache.get(func.getSpecId()))) {
                    ErrorConsts.BUSI_COMMON_ERROR.throwOut("请刷新产品缓存");
                }
                // 折扣信息
                if (KiteStringUtils.equalsAny(ProductCache.get(func.getSpecId()).getProdNbr(), "300000172", LocalKeyConsts.FUNC_PROD_ID_YF5GZF_ZK)) {
                    inst = func;
                }
            }
        }
        //0-∞档订购费
        String value = inst.getAttrValue("200003715");
        //折扣类型
        String discountType = inst.getAttrValue("200003712");
        if ("100006438".equals(discountType)) {
            //第一档
            value = inst.getAttrValue("200003717");
        }
        if (KiteStringUtils.isEmpty(value)) {
            value = KeyConsts.ZERO;
        }

        Double orderPrice = Double.valueOf(value);
        int laixianFee = SpringUtil.getBean(LocalSubscriptionFeeAttrLinkHandler.class).countLaixianFee(sceneInstId);
        orderPrice = DecimalCalc.sub(orderPrice, laixianFee);

        return orderPrice;
    }

    private Double getShareRate(KiteProdInstFunc inst) {
        String shareRate = inst.getAttrValue("200003713");
        if (KiteStringUtils.isEmpty(shareRate)) {
            shareRate = KeyConsts.ZERO;
        }
        return Double.valueOf(shareRate);
    }

    private Double getPlatformFuncFee(String sceneInstId, String custId) {
        String platFromFuncFee = KeyConsts.ZERO;
        KiteOfferInst mainOfferInst = querySceneInstService.getMainOfferInst(sceneInstId);
        List<KiteInstRelDTO> instRels = querySceneInstService.listInstRelsByAInst(custId, InstType.MAIN_OFFER_INST, mainOfferInst.getOfferInstId(), InstType.PROD_INST);
        if (!KiteListUtils.isEmpty(instRels)) {
            for (KiteInstRelDTO rel : instRels) {
                KiteProdInst prodInst = this.querySceneInstService.getProdInst(custId, rel.getzInstId());
                if (!KiteObjectUtils.isEmpty(prodInst) && !GoodsInfoTransfer.isAddRoleOffer(mainOfferInst.getSpecId(), OfferCache.get(mainOfferInst.getSpecId()).getCateId()) && !LocalKeyConsts.PROD_USE_TYPE_2000.equals(ProductCache.get(prodInst.getSpecId()).getProdUseType())) {
                    String platFromServLevel = prodInst.getAttrValue("200003681");
                    //平台功能费
                    platFromFuncFee = prodInst.getAttrValue("200004024");
                    if(KiteStringUtils.isEmpty(platFromFuncFee)) {
                    	platFromFuncFee = KeyConsts.ZERO;
                    }
                    //基础服务，平台功能费0
                    if ("100006416".equals(platFromServLevel)) {
                        platFromFuncFee = KeyConsts.ZERO;
                    }
                }
            }
        }
        return Double.valueOf(platFromFuncFee);
    }

    private KiteAttr getDiscountRateAttr(KiteProdInstFunc inst, String accProdInstId, String custId) {
        //折扣率
        KiteAttr discountAttr = inst.getAttr("200001694");
        if (!KiteObjectUtils.isEmpty(discountAttr)) {
            return discountAttr;
        }
        List<KiteInstRelDTO> prodInstFuncRels = querySceneInstService.listInstRelsByAInst(custId, InstType.PROD_INST, accProdInstId, InstType.PROD_INST_FUNC);
        for (KiteInstRelDTO funcRel : prodInstFuncRels) {
            KiteProdInstFunc func = this.querySceneInstService.getProdInstFunc(custId, funcRel.getzInstId());
            discountAttr = func.getAttr("200001694");
            if (!KiteObjectUtils.isEmpty(discountAttr)) {
                return discountAttr;
            }
        }
        return null;
    }

    /**
     *
     * @param inst 实例
     * @param discountAttr 折扣率属性
     * @param data 客户属性信息
     * @param totalStandarPrice 总价
     * @param platFromFuncFee 平台功能费
     * @param orderPrice 订购价格（分档折扣取第一档的最终订购价，不分档取0-∞最终订购价）
     * @param shareRate 折扣率
     */
    private void calculateDiscountRate(KiteProdInstFunc inst, KiteAttr discountAttr, AttrData data,
        Double totalStandarPrice, Double platFromFuncFee, Double orderPrice, Double shareRate) {
        double result = DecimalCalc.mul(totalStandarPrice, shareRate);
        result = DecimalCalc.mul(result, (1 + DecimalCalc.div(platFromFuncFee, 100)));
        BigDecimal resultBd = BigDecimal.valueOf(result);
        if (resultBd.compareTo(BigDecimal.ZERO) == 0){
//        if (result == 0) {
            super.set(discountAttr, inst, KeyConsts.ZERO, data);
        }
        else {
            double discount = DecimalCalc.div(orderPrice, result);
            discount = DecimalCalc.mul(discount, 100D);
            super.set(discountAttr, inst, String.format("%.2f", discount), data);
        }
    }
}
